#!usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask, jsonify, request
from config import DevConfig
from flask_sqlalchemy import SQLAlchemy
from Model.Model import User, Department, Doctor, ReserveNotes
from flask_uploads import UploadSet, configure_uploads, patch_request_class, IMAGES
import hashlib
import time


app = Flask(__name__)
app.config.from_object(DevConfig)
db = SQLAlchemy(app)
photos = UploadSet('PHOTO', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)


@app.route('/')
def index():
    return jsonify({'code': 200, 'msg': '项目启动成功', 'data': []})


@app.route('/add')
def add():
    user = User(username='flask', password='666666')
    if user:
        db.session.add(user)
        db.session.commit()
        return jsonify({'code': 200, 'msg': '添加用户成功', 'data': []})
    else:
        return jsonify({'code': 500, 'msg': '服务端错误，添加失败', 'data': []})


@app.route('/update/<string:username>')
def update(username):
    m = hashlib.md5()
    m.update('666666'.encode("utf8"))
    user = db.session.query(User).filter_by(username=username).update({'password': m.hexdigest()})
    if user:
        db.session.commit()
        return jsonify({'code': 200, 'msg': '修改成功', 'data': []})
    else:
        return jsonify({'code': 500, 'msg': '服务端错误，修改失败', 'data': []})


@app.route('/login', methods=['POST'])
def login():
    if request.json and request.method == 'POST':
        username = request.json['userName']
        password = request.json['password']
        m = hashlib.md5()
        m.update(password.encode("utf8"))
        user = User.query.filter_by(username=username).first()
        if not user:
            return jsonify({'code': 500, 'msg': '用户不存在', 'data': {}})
        if user.password == m.hexdigest():
            return jsonify({'code': 200, 'msg': '登录成功', 'data': {'userId': user.id, 'userName':user.username}})
        else:
            return jsonify({'code': 500, 'msg': '登录失败', 'data': {}})
    else:
        return jsonify({'code': 500, 'msg': '请求方式错误', 'data': {}})


@app.route('/delete/<string:table_id>')
def delete(table_id):
    user = User.query.get(table_id)
    if user:
        db.session.delete(user)
        db.session.commit()
        return jsonify({'code': 200, 'msg': '删除成功', 'data': []})
    else:
        return jsonify({'code': 500, 'msg': '用户不存在', 'data': []})


# 项目开始
@app.route('/department/add', methods=['POST'])
def departmentAdd():
    if request.json and request.method == 'POST':
        name = request.json['name']
        introduction = request.json['introduction']
        data = Department(name=name, introduction=introduction)
        if data:
            try:
                db.session.add(data)
                db.session.commit()
            except:
                return jsonify({'code': 500, 'msg': '该科室名已存在', 'data': []})
            return jsonify({'code': 200, 'msg': '添加科室成功', 'data': []})
        else:
            return jsonify({'code': 500, 'msg': '服务端错误，添加失败', 'data': []})
    else:
        return jsonify({'code': 500, 'msg': '请求方式错误', 'data': []})


@app.route('/department')
def department():
    name = request.args.get('name')
    if name:
        data = db.session.query(Department).filter(Department.name.like("%"+name+"%")).all()
    else:
        data = Department.query.all()
    if data:
        return jsonify({
            'code': 200,
            'msg': '获取科室成功',
            'data': [{
                'id': i.id,
                'name': i.name,
                'introduction': i.introduction
            } for i in data]
        })
    else:
        return jsonify({'code': 201, 'msg': '没有数据', 'data': []})
    
    
@app.route('/userInfo/<int:userId>')
def userInfo(userId):
    user = db.session.query(User).filter_by(id=userId).first()
    if user:
        return jsonify({'code': 200, 'msg': '成功获取用户信息', 'data': {
            'id': user.id,
            'userName': user.username,
            'trueName': user.trueName,
            'idCard': user.idCard,
            'socialNumber': user.socialNumber,
            'create_date': user.create_date.strftime("%Y-%m-%d %H:%M:%S")
        }})
    else:
        return jsonify({'code': 201, 'msg': '用户不存在', 'data': {}})


@app.route('/bind', methods=['POST'])
def bind():
    if request.json and request.method == 'POST':
        userId = request.json['userId']
        trueName = request.json['trueName']
        idCard = request.json['idCard']
        socialNumber = request.json['socialNumber']
        user = db.session.query(User).filter_by(id=userId).update({'trueName': trueName,
                                                                   'idCard': idCard,
                                                                   'socialNumber': socialNumber
                                                                   })
        if user:
            db.session.commit()
            return jsonify({'code': 200, 'msg': '绑定成功', 'data': {}})
        else:
            return jsonify({'code': 500, 'msg': '服务端错误，绑定失败', 'data': {}})
    else:
        return jsonify({'code': 500, 'msg': '请求方式错误', 'data': {}})


@app.route("/adddoctor", methods=['POST'])
def adddoctor():
    if request.form and request.method == 'POST':
        name = request.form['name']
        introduction = request.form['introduction']
        try:
            filename = photos.save(request.files['photo'])
        except :
            return jsonify({
                'code': 500,
                'msg': '你的文件类型不在'+str(IMAGES)+'范围内或文件名为中文不充许上传',
                'data': {}
            })
        photo = photos.url(filename)
        specialty = request.form['specialty']
        worker = request.form['worker']
        notes = request.form['notes']
        data = Doctor(name=name, photo=photo, introduction=introduction, specialty=specialty, worker=worker, notes=notes)
        if data:
            from random import randint
            depart = db.session.query(Department).all()
            data.tags.append(depart[randint(0, len(depart) - 1)])
            db.session.add(data)
            db.session.commit()
            return jsonify({'code': 200, 'msg': '添加医生成功', 'data': {}})
        else:
            return jsonify({'code': 500, 'msg': '服务端错误，添加失败', 'data': {}})
    else:
        return jsonify({'code': 500, 'msg': '请求方式错误', 'data': {}})


@app.route('/getdoctor/<int:departmentId>')
def getdoctor(departmentId):
    depart = db.session.query(Department).filter_by(id=departmentId).all()
    if depart and depart[0].doctor:
        return jsonify({'code': 200, 'msg': '获取医生成功', 'data': [{
            'id': i.id,
            'name': i.name,
            'photo': i.photo,
            'worker': i.worker,
            'introduction': i.introduction,
        } for i in depart[0].doctor]})
    else:
        return jsonify({'code': 201, 'msg': '没有数据', 'data': {}})


@app.route('/doctorInfo/<int:doctorId>')
def doctorInfo(doctorId):
    doctor = db.session.query(Doctor).filter_by(id=doctorId).first()
    if doctor:
        return jsonify({'code': 200, 'msg': '成功获取医生信息', 'data': {
            'id': doctor.id,
            'name': doctor.name,
            'photo': doctor.photo,
            'introduction': doctor.introduction,
            'specialty': doctor.specialty,
            'notes': doctor.notes,
            'worker': doctor.worker,
            'create_date': doctor.create_date.strftime("%Y-%m-%d %H:%M:%S")
        }})
    else:
        return jsonify({'code': 201, 'msg': '医生不存在', 'data': {}})


@app.route('/surplus/<int:doctorId>')
def surplus(doctorId):
    if request.args.get('time'):
        today = request.args.get('time')
    else:
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    surplusM = db.session.query(ReserveNotes).filter_by(
        doctor_id=doctorId,
        state=DevConfig.RESERVE_STATE_SUCCESS,
        how_reserve=DevConfig.RESERVE_DATE_MORNING,
    ).filter(ReserveNotes.reserve_date.between(today, today + ' 23:59:59')).count()
    surplusA = db.session.query(ReserveNotes).filter_by(
        doctor_id=doctorId,
        state=DevConfig.RESERVE_STATE_SUCCESS,
        how_reserve=DevConfig.RESERVE_DATE_AFTERNOON
    ).filter(ReserveNotes.reserve_date.between(today, today+ ' 23:59:59')).count()
    print(surplusM)
    # reduce = lambda x, y : x - y
    # morning = reduce(DevConfig.RESERVE_COUNT, 10)
    morning = (DevConfig.RESERVE_COUNT - surplusM, 0)[DevConfig.RESERVE_COUNT - surplusM <= 0]
    afternoon = (DevConfig.RESERVE_COUNT - surplusA, 0)[DevConfig.RESERVE_COUNT - surplusA <= 0]
    return jsonify({'code': 200, 'msg': '成功获取当前剩余', 'data': {'morning': morning, 'afternoon': afternoon}})


@app.route('/reserve', methods=['POST'])
def reserve():
    if request.json and request.method == 'POST':
        moment = request.json['department']
        reserve_date = request.json['reserve_date']
        how_reserve = request.json['how_reserve']
        money = request.json['money']
        user_id = request.json['user_id']
        doctor_id = request.json['doctor_id']
        today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        if reserve_date == DevConfig.RESERVE_DATE_MORNING:
            count = db.session.query(ReserveNotes).filter_by(
                doctor_id=doctor_id,
                how_reserve=DevConfig.RESERVE_DATE_MORNING,
            ).filter(ReserveNotes.reserve_date.between(today, today + ' 23:59:59')).count()
        else:
            count = db.session.query(ReserveNotes).filter_by(
                doctor_id=doctor_id,
                how_reserve=DevConfig.RESERVE_DATE_AFTERNOON
            ).filter(ReserveNotes.reserve_date.between(today, today + ' 23:59:59')).count()
        state = (DevConfig.RESERVE_STATE_SUCCESS, DevConfig.RESERVE_STATE_ERROR)[count >= 5]
        data = ReserveNotes(department=moment, reserve_date=reserve_date, how_reserve=how_reserve, money=money,
                            user_id=user_id, doctor_id=doctor_id, state=state)
        if data:
            try:
                db.session.add(data)
                db.session.commit()
            except:
                return jsonify({'code': 500, 'msg': '挂号失败', 'data': None})
            return jsonify({'code': 200, 'msg': '挂号成功', 'data': None})
        else:
            return jsonify({'code': 500, 'msg': '提交数据有误', 'data': None})
    else:
        return jsonify({'code': 500, 'msg': '请求方式错误', 'data': None})


@app.route('/getReserve/<int:userId>')
def getReserve(userId):
    data = db.session.query(ReserveNotes).filter_by(user_id=userId).all()
    if data:
        return jsonify({'code': 200, 'msg': '成功获取挂号记录', 'data':[{
            'id': i.id,
            'department': i.department,
            'reserve_date': i.reserve_date.strftime("%Y-%m-%d"),
            'how_reserve': i.how_reserve,
            'state': i.state,
            'money': i.money,
            'create_date': i.create_date.strftime("%Y-%m-%d %H:%M:%S"),
            'user_id': i.user_id,
            'doctor_id': i.doctor_id
        } for i in data]})
    else:
        return jsonify({'code': 201, 'msg': '没有数据', 'data':[]})


if __name__ == '__main__':
    app.run(host='0.0.0.0')
